<script setup lang="ts">
import RoomStatus from './components/RoomStatus.vue'
import RoomAction from './components/RoomAction.vue'
import RoomMessage from './components/RoomMessage.vue'
import io, { type Socket } from 'socket.io-client'
import { useRoute } from 'vue-router'
import { useUserStore } from '@/stores'
import { onMounted } from 'vue'
import { baseURL } from '@/utils/request'
import { onUnmounted } from 'vue'
import type { Message, TimeMessages } from '@/types/room'
import { MsgType, OrderType } from '@/enums'
import { ref } from 'vue'
import type { ConsultOrderItem, Image } from '@/types/consult'
import { getConsultOrderDetail } from '@/services/consult'
import { nextTick } from 'vue'
import dayjs from 'dayjs'
import { showToast } from 'vant'
import { provide } from 'vue'

const store = useUserStore()
const route = useRoute()
// 存储socket实例
let socket: Socket
const list = ref<Message[]>([])
const consult = ref<ConsultOrderItem>()
// 获取资讯订单后台详情信息
const loadConsult = async () => {
  const res = await getConsultOrderDetail(route.query.orderId as string)
  consult.value = res.data
}
provide('consult', consult)
// 成功后修改消息
const completeEva = (score: number) => {
  const item = list.value.find((item) => item.msgType === MsgType.CardEvaForm)
  if (item) {
    item.msg.evaluateDoc = { score }
    item.msgType = MsgType.CardEva
  }
}
provide('completeEva', completeEva)

onMounted(() => {
  // 页面加载时获取订单状态
  // 1.通过io函数传入后台ws连接地址和相关参数（token，orderid)
  // 2.建立连接成功后的相关事件：
  //     1.通过io实例的connect事件，监听连接是否成功
  //     2.通过io实例的error事件，监听连接错误
  //     3.通过io实例的disconnect事件，监听连接断开
  loadConsult()
  socket = io(baseURL, {
    auth: {
      token: `Bearer ${store.user?.token}`
    },
    query: {
      orderId: route.query.orderId
    }
  })
  socket.on('connect', () => {
    console.log('连接成功')
  })
  socket.on('disconnect', () => {
    console.log('断开连接')
  })
  socket.on('error', (err) => {
    console.log('发生错误', err)
  })

  // 监听订单状态---变更时刷新状态：接收订单变化的消息，重新更新一下
  socket.on('statusChange', () => loadConsult() )

  // 聊天记录
  socket.on('chatMsgList', ({ data }: { data: TimeMessages[] }) => {
    // 准备转换常规消息列表
    const arr: Message[] = []
    data.forEach((item, i) => {
      if (i === 0) {
        time.value = item.createTime
      }
      // 发送消息的时间放入到arr中
      arr.push({
        msgType: MsgType.Notify,
        msg: {
          content: item.createTime
        },
        createTime: item.createTime,
        id: item.createTime
      })
      // 把item的消息放入到arr中去
      arr.push(...item.items)
    })
    // 追加到聊天消息列表
    list.value.unshift(...arr)
    loading.value = false
    // 判断是否还有聊天记录  第一次加载消息列表，看最新消息
    if (!arr.length) {
      return showToast('没有更多聊天记录了')
    }
    nextTick(() => {
      if (initialMsg.value) {
        socket.emit('updateMsgStatus', arr[arr.length - 1].id)
        window.scrollTo(0, document.body.scrollHeight)
        initialMsg.value = false
      }
    })
  })

  // 接收聊天消息
  socket.on('receiveChatMsg', async (event) => {
    list.value.push(event)
    await nextTick()
    socket.emit('updateMsgStatus', event.id)
    // 改了数据之后的dom的更新是异步的，自动滚动会自动失效，用nextTick函数解决
    // 执行的时候返回值是一个promise
    // 发送完消息后自动滑动屏幕，滚动到聊天列表的最底部
    window.scrollTo(0, document.body.scrollHeight)
  })
})
onUnmounted(() => {
  // 关闭连接
  socket.close()
})
const onSendText = (text: string) => {
  // 发送消息需要   发送人 收消息的人 消息类型  消息内容
  socket.emit('sendChatMsg', {
    from: store.user?.id,
    to: consult.value?.docInfo?.id, //发消息人的id
    msgType: MsgType.MsgText, //接受消息的人=》接诊的医生
    msg: {
      content: text
    }
  })
}
const onSendImage = (image: Image) => {
  socket.emit('sendChatMsg', {
    from: store.user?.id,
    to: consult.value?.docInfo?.id,
    msgType: MsgType.MsgImage,
    msg: {
      picture: image
    }
  })
}
const loading = ref(false)
const initialMsg = ref(true)

const time = ref(dayjs().format('YYYY-MM-DD HH:mm:ss'))
const onRefresh = () => {
  // 触发刷新，发送获取聊天记录消息
  socket.emit('getChatMsgList', 20, time.value, route.query.orderId)
}
</script>

<template>
  <div class="room-page">
    <cp-nav-bar title="医生问诊室" />
    <!-- 消息状态 -->
    <room-status :status="consult?.status" :countdown="consult?.countdown"></room-status>
    <!-- 消息列表 -->
    <van-pull-refresh v-model="loading" @refresh="onRefresh">
      <room-message v-for="item in list" :key="item.id" :item="item"></room-message>
    </van-pull-refresh>
    <!-- 底部发送文字 -->
    <room-action
      :disabled="consult?.status !== OrderType.ConsultChat"
      @send-text="onSendText"
      @send-image="onSendImage"
    ></room-action>
  </div>
</template>

<style lang="scss" scoped>
.room-page {
  padding-top: 90px;
  padding-bottom: 60px;
  min-height: 100vh;
  box-sizing: border-box;
  background-color: var(--cp-bg);
  .van-pull-refresh {
    width: 100%;
    min-height: calc(100vh - 150px);
  }
}
</style>
